package br.senai.sc.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.senai.sc.dao.ProfessorDAO;
import br.senai.sc.entity.Professor;

@WebServlet({ "/salvarProfessor", "/listarProfessor", 
			  "/editarProfessor",	"/excluirProfessor" })

public class ProfessorController extends HttpServlet {

	private static final long serialVersionUID = 5591951452824484530L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String cmd = req.getParameter("cmd");

		if (cmd.equalsIgnoreCase("salvarProfessor")) {
			
				String idProfessor = req.getParameter("idProfessor");
				String nome = req.getParameter("nome");
				String cpf = req.getParameter("cpf");
				String endereco = req.getParameter("endereco");
				String email = req.getParameter("email");
				String telefone = req.getParameter("telefone");

				Professor p = new Professor();
				p.setNome(nome);
				p.setCpf(cpf);
				p.setEndereco(endereco);
				p.setEmail(email);
				p.setTelefone(telefone);

				if (idProfessor != null) {
					
					int idProfessorAux = new Integer(idProfessor);
					p.setIdProfessor(idProfessorAux);
					ProfessorDAO.alterar(p);
				
				} else {
					
					ProfessorDAO.inserir(p);
				
				}
				
			resp.sendRedirect("listarProfessor?cmd=listarProfessor");

		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String cmd = req.getParameter("cmd");

		if (cmd.equalsIgnoreCase("editarProfessor")) {
			
				String idProfessor = req.getParameter("idProfessor");
				Professor p = new Professor();
	
				p.setIdProfessor(Integer.valueOf(idProfessor));
				Professor professor = ProfessorDAO.findById(Integer.valueOf(idProfessor));
	
				req.setAttribute("professor", professor);
				req.getRequestDispatcher("/cadastros/cadProfessor.jsp").forward(req, resp);


		} else if (cmd.equalsIgnoreCase("listarProfessor")) {
	
				List<Professor> professores = ProfessorDAO.getAll();
	
				req.setAttribute("professores", professores);
				req.getRequestDispatcher("cadastros/listarProfessor.jsp").forward(req, resp);

		} else if (cmd.equalsIgnoreCase("excluirProfessor")) {
			
				Integer idProfessor = new Integer(req.getParameter("idProfessor"));
				Professor p = new Professor();
				
					if (idProfessor != 0) {
						
						p.setIdProfessor(Integer.valueOf(idProfessor));
						ProfessorDAO.excluir(p);
						
					} else {
						
						ProfessorDAO.getAll();
						
					}
				resp.sendRedirect("listarProfessor?cmd=listarProfessor");
		}
	}

}
